package com.march.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.march.common.R;
import com.march.dto.DishDTO;
import com.march.entry.Dish;
import com.march.entry.DishFlavor;
import com.march.mapper.DishMapper;
import com.march.service.DishFlavorService;
import com.march.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;
    /*
    * 新增菜品同时增加口味数据
    * 一个表单的数据保存到两个表中
    * */
    @Transactional
    @Override
    public void saveWithFlavor(DishDTO dishDto) {
        //保存菜品基本信息到菜品表
        this.save(dishDto);
        //保存菜品口味数据到口味表

        Long dishId = dishDto.getId();
        //获取到flavor列表
        List<DishFlavor> flavors = dishDto.getFlavors();

        flavors = flavors.stream().map(item -> {
            item.setDishId(dishId);
            return item;
        }).collect(Collectors.toList());

        dishFlavorService.saveBatch(flavors);
    }

    /*
    * 读取菜品信息的和口味，两张表
    * */
    @Override
    public DishDTO getByIdWithFlavor(Long id) {

        DishDTO dishDTO = new DishDTO();
        // 获取id的菜品
        Dish dishById = this.getById(id);
        // 根据菜品的id获取菜品的口味
//        DishFlavor byId = dishFlavorService.getById(dishById.getId());
        LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
        lqw.eq(DishFlavor::getDishId, dishById.getId());
        List<DishFlavor> flavors = dishFlavorService.list(lqw);

        dishDTO.setFlavors(flavors);
        BeanUtils.copyProperties(dishById, dishDTO);

        return dishDTO;
    }

    /*
    * 更新菜品的操作
    * */
    @Override
    public void updateWithFlavor(DishDTO dishDTO) {

        //更新菜品基本信息
        this.updateById(dishDTO);

        //删除菜品的口味信息
        LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
        lqw.eq(DishFlavor::getDishId,dishDTO.getId());
        dishFlavorService.remove(lqw);

        //处理更新的菜品口味信息
        List<DishFlavor> flavors = dishDTO.getFlavors();
        flavors = flavors.stream().map(item -> {
            item.setDishId(dishDTO.getId());
            return item;
        }).collect(Collectors.toList());
        dishFlavorService.saveBatch(flavors);
    }
}
